package com.qyhl.webtv.module_news.news.comment;

import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.entity.news.NormalNewsBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/11/29.
 * 评论详情页
 */
@Route(path = ARouterPathConstant.NEWS_COMMENT)
public class CommentActivity extends BaseActivity implements CommentContract.CommentView, BaseActivity.InputListener {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.editbar)
    EditBar editbar;
    @BindView(R2.id.listview)
    ListView listview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.back_btn)
    ImageView backBtn;

    private CommentPresenter mPresenter;
    private boolean editbarEnable = true;

    private String newsId;

    private String sectionId;

    private String commentId = "0";

    private String mTitle;

    private RequestOptions options;

    private List<NormalNewsBean.ArticleComment> mList;

    private LoadingDialog.Builder builder;

    private CommonAdapter<NormalNewsBean.ArticleComment> commonAdapter;

    private String commentContent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_comment;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new CommentPresenter(this);
        newsId = getIntent().getStringExtra("id");
        sectionId = getIntent().getStringExtra("sectionId");
        mTitle = getIntent().getStringExtra("title");
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getComment(newsId, commentId);
    }


    /**
     * 初始化
     */
    private void initView() {
        addInputListener(this);
        loadMask.setStatus(LoadingLayout.Loading);

        title.setText("全部评论");

        mList = new ArrayList<>();

        //配置刷新
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);
        refresh.setDisableContentWhenRefresh(true);
        refresh.setDisableContentWhenLoading(true);

        //glide配置
        options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.comment_head_default)
                .error(R.drawable.comment_head_default)
                .transform(new GlideCircleTransform(this))
                .priority(Priority.HIGH);

        //评论
        listview.setAdapter(commonAdapter = new CommonAdapter<NormalNewsBean.ArticleComment>(this, R.layout.news_item_comment, mList) {
            @Override
            protected void convert(ViewHolder holder, NormalNewsBean.ArticleComment item, int position) {
                holder.setText(R.id.nickName, item.getCommentuser());
                holder.setText(R.id.content, item.getContent());
                holder.setText(R.id.publish_date, DateUtils.mTranslateDate(item.getAddtime()));
                ImageView headIcon = holder.getView(R.id.head_icon);

                Glide.with(getApplicationContext())
                        .load(item.getLogo())
                        .apply(options)
                        .into(headIcon);
            }
        });

        editbar.changeStateSend(this);
        editbar.hideCollect(true);//隐藏工具栏
        editbar.hideComment(true);//隐藏工具栏
        editbar.hideShare(true);//隐藏工具栏

        builder = new LoadingDialog.Builder(CommentActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                commentId = "0";
                mPresenter.getComment(newsId, commentId);
            }
        });

        //加载
        refresh.setOnLoadMoreListener(refreshlayout -> mPresenter.getComment(newsId, commentId));

        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            commentId = "0";
            mPresenter.getComment(newsId, commentId);
        });

        //返回
        backBtn.setOnClickListener(v -> finish());

        //输出框监听
        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (editbarEnable) {
                    editbarEnable = false;

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                commentContent = editbar.getContent();
                                if (StringUtils.isEmpty(commentContent)) {
                                    Toasty.normal(CommentActivity.this, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
                                    editbarEnable = true;
                                } else {
                                    builder.show();
                                    String nickName = CommonUtils.getInstance().getNickName();
                                    mPresenter.sendComment(mTitle, sectionId, "1", newsId, nickName, commentContent);
                                    editbar.clearContent();
                                    hideInput();//隐藏软键盘
                                }
                            } else {
                                Toasty.normal(CommentActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                RouterManager.routerLogin(CommentActivity.this, 0);
                                editbarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            editbarEnable = true;
                        }
                    });

                }
            }
        });
    }

    /**
     * 设置评论数据
     *
     * @param beanList
     * @param isMore
     */
    @Override
    public void setComment(List<NormalNewsBean.ArticleComment> beanList, boolean isMore) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        try {
            commentId = beanList.get(beanList.size() - 1).getCommentid();
        } catch (Exception e) {
            commentId = "0";
        }
        if (isMore) {
            mList.addAll(beanList);
        } else {
            mList.clear();
            mList.addAll(beanList);
        }

        commonAdapter.notifyDataSetChanged();
    }

    /**
     * 发送评论失败
     *
     * @param msg
     */
    @Override
    public void sendError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        editbarEnable = true;
    }

    /**
     * 发送评论成功
     *
     * @param msg
     */
    @Override
    public void sendSuccess(String msg) {
        builder.dismiss();
        editbar.changeStateDefault(this);
        editbarEnable = true;

        int commentRule = Integer.parseInt(CommonUtils.getInstance().getCommentRule());
        if (commentRule == 0) {
            Toasty.normal(this, "评论成功！").show();
            commentId = "0";
            mPresenter.getComment(newsId, commentId);
            BusFactory.getBus().post(new Event.commentAdd());
        } else {
            Toasty.normal(this, "评论成功，等待审核！").show();
        }

        String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        if (integralSwitch.equals("1")) {
            getCoin();
        }

        //四川融媒统计
        if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
            StatisticsMainInit.commentaryLog(CommonUtils.getInstance().getUserName(), newsId, mTitle, commentContent);
        }
    }


    @Override
    public void getCoinSuccess(CoinBean coinBean) {
        Toasty.normal(CommentActivity.this, "评论成功，获得" + coinBean.getCoin() + "金币！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getCoinError(String msg) {
        Log.e("error_comment", msg);
    }

    private void getCoin() {
        mPresenter.getCoin();
    }
    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setEmptyText(msg);
        loadMask.setEmptyImage(R.drawable.empty_comment);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * toast
     *
     * @param msg
     */
    @Override
    public void showMessage(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * log
     *
     * @param msg
     */
    @Override
    public void showLog(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setReloadButtonText("点击重试~~");
    }




    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("全部评论");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("全部评论");
        MobclickAgent.onPause(this);
    }

    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        editbar.changeStateDefault(this);
    }
}
